package api

import (
	"context"
	"encoding/json"
	"fmt"
	"image_demo/internal/constants"
	"io"
	"math/rand"
	"net/http"
)

// Client 表示API客户端
type Client struct {
	httpClient *http.Client
}

// NewClient 创建新的API客户端
func NewClient() *Client {
	return &Client{
		httpClient: createHttpClient(),
	}
}

// 创建带防限流配置的HTTP客户端
func createHttpClient() *http.Client {
	return &http.Client{
		Timeout: constants.HTTPTimeout,
		Transport: &http.Transport{
			MaxIdleConns:        constants.MaxIdleConns,
			IdleConnTimeout:     constants.IdleConnTimeout,
			DisableCompression:  true,
			DisableKeepAlives:   false,
			MaxIdleConnsPerHost: constants.MaxIdleConnsPerHost,
		},
	}
}

// 获取随机User-Agent
func getRandomUserAgent() string {
	return constants.UserAgents[rand.Intn(len(constants.UserAgents))]
}

// Call 调用API接口
func (c *Client) Call(ctx context.Context, apiURL string) (string, error) {
	req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
	if err != nil {
		return "", fmt.Errorf("创建请求失败: %v", err)
	}

	// 设置随机请求头防限流
	req.Header.Set(constants.UserAgentHeader, getRandomUserAgent())
	req.Header.Set(constants.AcceptHeader, constants.DefaultAccept)
	req.Header.Set(constants.AcceptLanguageHeader, constants.DefaultAcceptLanguage)
	req.Header.Set(constants.ConnectionHeader, constants.DefaultConnection)
	req.Header.Set(constants.RefererHeader, constants.DefaultReferer)
	req.Header.Set(constants.OriginHeader, constants.DefaultOrigin)

	resp, err := c.httpClient.Do(req)
	if err != nil {
		return "", fmt.Errorf("API请求失败: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != constants.HTTPStatusOK {
		return "", fmt.Errorf("API返回非200状态码: %d", resp.StatusCode)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("读取响应体失败: %v", err)
	}

	var apiResp Response
	if err := json.Unmarshal(body, &apiResp); err != nil {
		return "", fmt.Errorf("解析JSON响应失败: %v", err)
	}

	if apiResp.Code != constants.APISuccessCode {
		return "", fmt.Errorf("API返回错误: %s (请求ID: %s)", apiResp.Msg, apiResp.RequestID)
	}

	return apiResp.Data, nil
}

// SelectRandomAPIs 随机选择API接口
func SelectRandomAPIs(count int) []string {
	if count > len(constants.APIEndpoints) {
		count = len(constants.APIEndpoints)
	}

	// 打乱API列表
	shuffled := make([]string, len(constants.APIEndpoints))
	copy(shuffled, constants.APIEndpoints)
	rand.Shuffle(len(shuffled), func(i, j int) {
		shuffled[i], shuffled[j] = shuffled[j], shuffled[i]
	})

	return shuffled[:count]
}
